import 'dart:convert';
import '../models/api_response.dart';
import '../models/chat_model.dart';
import '../services/api_service.dart';
import '../constants/api_endpoints.dart';

class ChatRepository {
  final ApiService _apiService;

  ChatRepository(this._apiService);

  /// 获取单聊消息列表
  Future<ApiResponse<List<ChatModel>>> getSingleChatMessages({
    int? toUserId,
    int? limit,
    int? offset,
  }) async {
    final queryParams = <String, dynamic>{};
    if (toUserId != null) queryParams['to_user_id'] = toUserId;
    if (limit != null) queryParams['limit'] = limit;
    if (offset != null) queryParams['offset'] = offset;

    final response = await _apiService.get<List<ChatModel>>(
      ApiEndpoints.imMessagesSingleList,
      queryParameters: queryParams,
      fromJson: (json) {
        if (json is List) {
          return json
              .map((item) => ChatModel.fromJson(item as Map<String, dynamic>))
              .toList();
        }
        return [];
      },
    );

    return response;
  }

  /// 发送通话邀请
  /// [fromId] 发送者的 open_id
  /// [toId] 接收者的 open_id
  /// [isVoiceOnly] 是否仅语音通话
  /// [timeout] 超时时间（秒），默认30秒
  Future<ApiResponse<ChatModel>> sendCallInvite({
    required String fromId,
    required String toId,
    required bool isVoiceOnly,
    int timeout = 30,
  }) async {
    // 构建通话邀请消息内容（JSON格式）
    final inviteContent = jsonEncode({
      'type': 'call_invite',
      'isVoiceOnly': isVoiceOnly,
      'timeout': timeout,
      'timestamp': DateTime.now().millisecondsSinceEpoch,
    });
    
    return sendSingleMessage(
      fromId: fromId,
      toId: toId,
      messageBody: inviteContent,
      messageContentType: 4, // 通话邀请类型
    );
  }

  /// 发送通话取消/结束消息
  /// [fromId] 发送者的 open_id
  /// [toId] 接收者的 open_id
  Future<ApiResponse<ChatModel>> sendCallCancel({
    required String fromId,
    required String toId,
  }) async {
    // 构建通话取消消息内容（JSON格式）
    final cancelContent = jsonEncode({
      'type': 'call_cancel',
      'timestamp': DateTime.now().millisecondsSinceEpoch,
    });
    
    return sendSingleMessage(
      fromId: fromId,
      toId: toId,
      messageBody: cancelContent,
      messageContentType: 5, // 通话取消类型
    );
  }

  /// 发送单聊消息
  /// [fromId] 发送者的 open_id
  /// [toId] 接收者的 open_id
  /// [messageBody] 消息内容
  /// [messageContentType] 消息内容类型：1=文本，2=图片，3=文件，4=语音/视频通话
  Future<ApiResponse<ChatModel>> sendSingleMessage({
    required String fromId,
    required String toId,
    required String messageBody,
    int messageContentType = 1,
    String? extra,
  }) async {
    final response = await _apiService.post<ChatModel>(
      ApiEndpoints.imMessagesSingle,
      data: {
        'from_id': fromId,
        'to_id': toId,
        'message_body': messageBody,
        'message_content_type': messageContentType,
        if (extra != null) 'extra': extra,
      },
      fromJson: (json) {
        // 后端可能返回不同的格式，需要灵活处理
        if (json is Map<String, dynamic>) {
          // 如果响应中有 message_id 或其他字段，尝试解析
          // 注意：后端可能返回 {status: "ok", message_id: "..."} 格式
          if (json.containsKey('message_id') || json.containsKey('id')) {
            // 尝试解析为 ChatModel
            try {
              return ChatModel.fromJson(json);
            } catch (e) {
              // 如果解析失败，返回一个基本的 ChatModel
              return ChatModel(
                id: json['id'] ?? int.tryParse(json['message_id']?.toString() ?? '0') ?? 0,
                chatId: json['chat_id'] ?? 0,
                fromUserId: int.tryParse(fromId) ?? 0,
                toUserId: int.tryParse(toId) ?? 0,
                content: messageBody,
                messageType: messageContentType,
                status: 1,
              );
            }
          }
          // 标准 ChatModel 格式
          return ChatModel.fromJson(json);
        }
        // 如果不是 Map，返回一个基本的 ChatModel
        return ChatModel(
          id: 0,
          chatId: 0,
          fromUserId: int.tryParse(fromId) ?? 0,
          toUserId: int.tryParse(toId) ?? 0,
          content: messageBody,
          messageType: messageContentType,
          status: 1,
        );
      },
    );

    return response;
  }
}

